/**
 * Created by dingyuxuan on 2018/3/15.
 */
import Tree from './tree'
import { Base64 } from 'js-base64'

const getIdx = (c) => {
  if (!c || typeof c !== 'string') {
    return 0
  }
  const x = c.charCodeAt(0)
  if (x >= 65) {
    return x - 65
  }
  return x - 65 + 41
}

const VERSION = 1

const checkVersion = (s) => {
  const wi = getIdx(s[0]) * 32 + getIdx(s[1])
  const x = getIdx(s[2])
  const check = getIdx(s[3])

  return VERSION >= (wi * x + check) % 32
}

export const decode = (enc) => {
  if (!enc || typeof enc !== 'string') {
    return ''
  }

  if (!checkVersion(enc)) {
    return ''
  }

  const tree = new Tree()
  tree.init(enc.substring(0, 4))
  const rawEncode = tree.decode(enc)

  return Base64.decode(rawEncode)
}
